/**
 * JPADAOImpl.java
 * 
 * $Source$
 */
/*
 * Copyright (c) 2012 MyDoctor.com, Inc. All rights reserved.
 */

package com.mydoctor.dao.impl;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.mydoctor.dao.DAO;
import com.mydoctor.util.MyDoctorConstants;
import com.mydoctor.util.MyDoctorMessages;

/**
 * @author krovi
 * @version $Id$
 */
public abstract class DAOImpl<T> implements DAO<T>
{
    @PersistenceContext(unitName = MyDoctorConstants.MYDOCTOR_PERSISTENT_UNIT)
    private EntityManager entityManager;

    @Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
    public boolean delete(T obj)
    {
        if (null == obj)
        {
            throw new IllegalArgumentException(MyDoctorMessages.NULL_OBJECT);
        }
        getEntityManager().remove(obj);
        return true;
    }

    protected EntityManager getEntityManager()
    {
        return entityManager;
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public T insert(T obj)
    {
        if (null == obj)
        {
            throw new IllegalArgumentException(MyDoctorMessages.NULL_OBJECT);
        }
        getEntityManager().persist(obj);
        getEntityManager().flush();
        return obj;
    }

    @Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
    public T update(T obj)
    {
        if (null == obj)
        {
            throw new IllegalArgumentException(MyDoctorMessages.NULL_OBJECT);
        }
        T managedObj = getEntityManager().merge(obj);
        return managedObj;
    }

}
